package com.chai.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.chai.constant.MessageConstant;
import com.chai.constant.RedisConstant;
import com.chai.pojo.Setmeal;
import com.chai.service.SetmealService;
import com.chai.utils.QiniuUtils;
import com.chai.vo.PageResult;
import com.chai.vo.QueryPageBean;
import com.chai.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/Setmeal")
public class SetmealController {

    @Reference
    SetmealService setmealService;

    @Autowired
    JedisPool jedisPool;

    @PostMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = setmealService.findPage(queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString());
        return pageResult;
    }

    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile imgFile) {
        try {
            byte[] bytes = imgFile.getBytes();
            String originalFilename = imgFile.getOriginalFilename();

            String newFilename = UUID.randomUUID().toString() + "_" + originalFilename;
//            QiniuUtils.upload2Qiniu(bytes,originalFilename);

            QiniuUtils.upload2Qiniu(bytes, newFilename);

            //记录图片名称，存在垃圾图片
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,newFilename);

            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, newFilename);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.PIC_UPLOAD_FAIL);

        }
    }

    @PostMapping("/add")
    public Result add(Integer[] travelgroupIds, @RequestBody Setmeal setmeal) {
        try {
            setmealService.add(travelgroupIds, setmeal);
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }

    }
}
